package edu.cuit.canary.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

/**
 * 处理http协议的servlet
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/2 15:05
 */
@WebServlet("/third")
public class ThirdServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数
        String username = request.getParameter("username");
        String age = request.getParameter("age");
        //获取复选框(多个值)的请求参数
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println("username:" + username);
        System.out.println("age:" + age);
        System.out.println("hobbies:" + Arrays.toString(hobbies));
        System.out.println("========================================");
        Enumeration<String> names = request.getParameterNames();
        while(names.hasMoreElements()){
            var name = names.nextElement();
            System.out.println(name + ":" + Arrays.toString(request.getParameterValues(name)));
        }
        System.out.println("========================================");
        Map<String, String[]> map = request.getParameterMap();
        map.forEach((k, v) -> System.out.println(k + ":" + Arrays.toString(v)));
    }

    //处理post请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        for(var entry : parameterMap.entrySet()){
            System.out.println(entry.getKey() + ":" + Arrays.toString(entry.getValue()));
        }
        System.out.println("==========================获取请求头信息=======================");
        System.out.println(req.getHeader("User-Agent"));
        Enumeration<String> headerNames = req.getHeaderNames();
        while(headerNames.hasMoreElements()){
            var name = headerNames.nextElement();
            System.out.println(name + ":" + req.getHeaders(name));
        }
    }
}
